package com.bbs.toutiao.service.client.impl;


import com.bbs.toutiao.aspect.SysLog;
import com.bbs.toutiao.mapper.clinet.ClientChatMapper;
import com.bbs.toutiao.service.client.SseService;
import com.bbs.toutiao.utils.ChatUtil;
import com.bbs.toutiao.vo.client.ChatVo;
import com.bbs.toutiao.vo.comm.PageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 描述:
 * 作者： zhangBin
 * 时间： 2024/4/1 16:27
 * 版本： 1.0
 */
@Slf4j
@Service
public class SseServiceImpl implements SseService {

    @Resource
    private ClientChatMapper clientChatMapper;

    @Resource
    private ChatUtil chatUtil;

    //创建sse
    @Override
    public SseEmitter createSse(String uid) {
        return chatUtil.createSSE(uid);
    }


    //指定用户发送消息
    @Override
    public Boolean sendMessage(Integer uid, String message, String uuid, String imgUrl, Integer redirectId) {
        return chatUtil.sendClientMSG(uid, message, uuid, imgUrl, redirectId);
    }


    /**
     * 查询
     *
     * @param time
     * @param timeEnd
     * @param userId
     * @param receiverId
     * @return
     */
    @Override
    public List<ChatVo> queryMessage(String time, String timeEnd, Integer userId, Integer receiverId) {

        return clientChatMapper.selectChatByTime(time, timeEnd, userId, receiverId);
    }


    //分页查询聊天记录
    @Override
    public PageVo<ChatVo> queryMessageByPage(int page, int size, Integer userId, Integer receiverId) {
        List<ChatVo> list = clientChatMapper.selectChatByPage(page, size, userId, receiverId);
        int count = clientChatMapper.selectChatCountByUserId(userId, receiverId);
        Collections.reverse(list);
        PageVo<ChatVo> pageVo = new PageVo<>();
        pageVo.setTotal(count);
        pageVo.setPageList(list);
        return pageVo;
    }

    /**
     * 查询用户关注的人（好友）
     *
     * @param userId
     * @return
     */
    @Override
    public List<ChatVo> queryFollowsList(int userId, String type) {
        List<ChatVo> chatVosList;
        if (Objects.equals(type, "CHAT")) {
            chatVosList = clientChatMapper.followsByUserId(userId);
            List<Integer> receiverIdList = chatVosList.stream().map(ChatVo::getReceiverId).collect(Collectors.toList());
            List<ChatVo> batchList = clientChatMapper.getLatestMessagesBatch(userId, receiverIdList);
            chatVosList.forEach(e -> {
                ChatVo chatVo = batchList.stream()
                        .filter(f ->
                                Objects.equals(f.getReceiverId(), e.getReceiverId()) || Objects.equals(f.getSenderId(), e.getReceiverId()))
                        .max(Comparator.comparing(ChatVo::getSendTime)).orElse(null);
                if (chatVo != null) {
                    e.setMessage(chatVo.getMessage());
                    e.setImageUrl(chatVo.getImageUrl());
                }
            });
            return chatVosList;
        } else if (Objects.equals(type, "FOLLOW_ING")) {
            //查询粉丝
            chatVosList = clientChatMapper.followIngByUserId(userId);
        } else {
            chatVosList = clientChatMapper.followsByUserIdAndAll(userId);
        }
        return chatVosList;
    }


    /**
     * 已读
     *
     * @param userId
     * @param toUid
     * @return
     */
    @Override
    public Boolean readMessage(Integer userId, Integer toUid) {
        //同时给前端发送用户是否在线
        return clientChatMapper.updateIsDeSend(userId, toUid) > 0;
    }


    //清空聊天记录
    @SysLog("用户清空聊天记录")
    @Override
    public Boolean deleteMessage(Integer userId, Integer touid) {

        return clientChatMapper.deleteChat(userId, touid) > 0;
    }


}
